package com.wangshuqi.jdbc.pool;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBCPDataSourcePool {


    private static DataSource dataSource;

    static {
        try {
            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.properties");
            Properties properties = new Properties();
            properties.load(is);
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection1() throws SQLException {
        Connection connection = dataSource.getConnection();
        return connection;
    }

    // 硬编码方式 -- 不推荐
    public static Connection getConnection() throws Exception {
        BasicDataSource source = new BasicDataSource();

        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql:///test");
        source.setUsername("root");
        source.setPassword("123456");

        source.setInitialSize(10);

        Connection conn = source.getConnection();
        return conn;
    }


    @Test
    public void test() throws Exception {
        Connection connection = getConnection1();
        System.out.println(connection);
    }
}
